package com.java.zhuiyun.api.series_course.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.java.zhuiyun.api.back_course.entity.BackCourse;
import com.java.zhuiyun.api.back_course.model.BackCourseModel;
import com.java.zhuiyun.api.series_course.entity.SeriesCourse;
import com.java.zhuiyun.api.series_course.mapper.SeriesCourseMapper;
import com.java.zhuiyun.api.series_course.model.DictSeriesModel;
import com.java.zhuiyun.api.series_course.model.SeriesCourseModel;
import com.java.zhuiyun.api.series_course.service.SeriesCourseService;
import com.java.zhuiyun.api.sys_dict.entity.SysDict;
import com.java.zhuiyun.common.response.CommonResult;
import com.java.zhuiyun.util.UploadFileUtils;
import com.java.zhuiyun.util.pageUtil.MybatisPageHelper;
import com.java.zhuiyun.util.pageUtil.PageRequest;
import com.java.zhuiyun.util.pageUtil.PageResult;
import com.sun.xml.bind.v2.TODO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName SeriesCourseServiceImpl
 * @Description TODO
 * @Author 杨友朋
 * @Date 2023/8/30 11:31
 **/
@Service
public class SeriesCourseServiceImpl implements SeriesCourseService{
    @Resource
    SeriesCourseMapper seriesCourseMapper;

    /**
    * @Author 杨友朋
    * @Description TODO 添加系列课程
    * @Date 2023/8/30 14:42
    * @Return
    * @param
    */
    @Override
    @Transactional
    public CommonResult insertSeries(MultipartFile file, SeriesCourseModel seriesCourseModel) {
        // 判断介绍图片
        if(file!=null){
            // 判断是否存入服务器
            String s = UploadFileUtils.uploadFile(file);
            if(!s.equals("")){
                SeriesCourse seriesCourse=new SeriesCourse();
                BeanUtil.copyProperties(seriesCourseModel,seriesCourse);
                seriesCourse.setCreateTime(new Date());
                seriesCourse.setUpdateTime(new Date());
                seriesCourse.setSubjectImage(s);
                seriesCourseMapper.insertSelective(seriesCourse);
                return CommonResult.ok("保存成功");
            }
            return CommonResult.error(500,"上传图片失败");
        }
        return CommonResult.error(500,"请选择图片");
    }
    @Override
    public CommonResult upSeries(MultipartFile file, SeriesCourseModel seriesCourseModel) {
        SeriesCourse seriesCourse=new SeriesCourse();
        // 判断介绍图片
        if(file!=null){
            // 判断是否存入服务器
            String s = UploadFileUtils.uploadFile(file);
            if(s.equals("")){
                return CommonResult.error(500,"上传图片失败");
            }
            seriesCourseModel.setSubjectImage(s);
        }

        BeanUtil.copyProperties(seriesCourseModel,seriesCourse);
        seriesCourse.setUpdateTime(new Date());

        seriesCourseMapper.updateSelective(seriesCourse);
        return CommonResult.ok("保存成功");
    }

    @Override
    public CommonResult delCourse(Integer id) {
        if(id!=null||id!=0){
            Integer integer = seriesCourseMapper.delCourse(id);
            if(integer>0){
                return CommonResult.ok();
            }
            return CommonResult.error(500,"系统繁忙");
        }

        return CommonResult.error(500,"id为null");
    }

    @Override
    public CommonResult upSwitch(SeriesCourse seriesCourse) {
        seriesCourse.setUpdateTime(new Date());
        seriesCourseMapper.upSwitch(seriesCourse);
        return CommonResult.ok();
    }

    @Override
    public PageResult selectSeries(SeriesCourseModel seriesCourseModel, PageRequest pageResult) {
        MybatisPageHelper.startPage(pageResult);
        List<SeriesCourseModel> seriesCourseModels=seriesCourseMapper.selectSeries(seriesCourseModel);
        return MybatisPageHelper.getPageResult(seriesCourseModels);
    }

    @Override
    public PageResult teacherSelectSeries(SeriesCourseModel seriesCourseModel, PageRequest pageResult) {
        MybatisPageHelper.startPage(pageResult);
        List<SeriesCourseModel> seriesCourseModels=seriesCourseMapper.teacherSelectSeries(seriesCourseModel);
        return MybatisPageHelper.getPageResult(seriesCourseModels);
    }

    @Override
    public List<DictSeriesModel> selectCourse(Integer teacherId) {
        // 从数据库中查询字典项和 BackCourseModel 对象
        List<DictSeriesModel> dict = seriesCourseMapper.selectDict();
        // BackCourseModel 对象
        List<BackCourseModel> backCourseModels = seriesCourseMapper.selectBackCourse(teacherId);

        // 将字典项和 BackCourseModel 对象存入哈希表中
        Map<Integer, DictSeriesModel> dictMap = new HashMap<>();
        // 哈希表存储 BackCourseModel 对象
        Map<Integer, List<BackCourseModel>> backCourseMap = new HashMap<>();
        for (DictSeriesModel dictSeriesModel : dict) {
            // 筛选出根级别的字典项
            if (dictSeriesModel.getPrentId() == null) {
                // 将根字典项存入哈希表
                dictMap.put(dictSeriesModel.getId(), dictSeriesModel);
            }
            else {
                // 存储字典项的子项
                DictSeriesModel parentDict = dictMap.get(dictSeriesModel.getPrentId());
                if (parentDict != null) {
                    parentDict.getChildren().add(dictSeriesModel);
                    dictMap.put(dictSeriesModel.getId(), dictSeriesModel);
                }
            }
        }
        for (BackCourseModel backCourseModel : backCourseModels) {
            // 得到 BackCourseModel 对象列表或者新建一个列表
            List<BackCourseModel> subjectCourses = backCourseMap.getOrDefault(backCourseModel.getSubjectId(), new ArrayList<>());
            // 将对象加入列表中
            subjectCourses.add(backCourseModel);
            // 将列表存入哈希表中
            backCourseMap.put(backCourseModel.getSubjectId(), subjectCourses);
        }

        // 组织树形结构，将 BackCourseModel 对象添加到对应的字典项中
        List<DictSeriesModel> rootDict = dict.stream()
                .filter(dictSeriesModel -> dictSeriesModel.getPrentId() == null)
                .peek(dictSeriesModel -> {
                    List<BackCourseModel> subjectCourses = backCourseMap.get(dictSeriesModel.getId());
                    if (subjectCourses != null) {
                        dictSeriesModel.getSeriesCourseModels().addAll(subjectCourses);
                    }
                })
                .collect(Collectors.toList()); // 搜集根字典项
        // 递归处理每个根字典项的子项
        for (DictSeriesModel r : rootDict) {
            organizeChildren(r, dictMap, backCourseMap);
        }
        // 返回处理后的根字典项列表
        return rootDict;
    }

    @Override
    public CommonResult selectCheck(Integer id) {
        SeriesCourse s = seriesCourseMapper.selectCheck(id);
        String[] result;
        if (s.getCourseIds() == null) {
            String[] emptyIntArray = new String[0];
            return CommonResult.ok(emptyIntArray);
        }
        String courseIds = s.getCourseIds();


         if (courseIds.contains(",")) {
            result = courseIds.split(",");
            } else {
            result = courseIds.isEmpty() ? new String[0] : new String[]{s.getCourseIds()};
        }

        return CommonResult.ok(result);
    }

    @Override
    public CommonResult addCourse(SeriesCourseModel seriesCourse) {
        List<String> courseIds = seriesCourse.getCourseIds();
        if (courseIds.size() != 0) {
            StringBuffer stringBuffer = new StringBuffer();
            if (courseIds.size() > 1) {
                for (int i = 0; i < courseIds.size(); i++) {
                    stringBuffer.append(courseIds.get(i));
                    if (i < courseIds.size() - 1) {
                        stringBuffer.append(",");
                    }
                }
            } else {
                stringBuffer.append(courseIds.get(0));
            }
            String result = stringBuffer.toString(); // 最后的拼接结果
            SeriesCourse s=new SeriesCourse();
            s.setCourseIds(result);
            s.setUpdateTime(new Date());
            s.setId(seriesCourse.getId());
            Integer integer = seriesCourseMapper.addCourse(s);
            if(integer>0){
                return CommonResult.ok();
            }
            return CommonResult.error(500,"保存失败");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult selectById(Integer id) {
        SeriesCourseModel seriesCourseModel=seriesCourseMapper.selectById(id);
        return CommonResult.ok(seriesCourseModel);
    }


    /**
    * @Author 杨友朋
    * @Description TODO 处理字典项的子项，递归调用自己
    * @Date 2023/8/31 16:03
    * @Return
    * @param
    */
    private void organizeChildren(DictSeriesModel parentDict, Map<Integer, DictSeriesModel> dictMap, Map<Integer, List<BackCourseModel>> backCourseMap) {
        List<DictSeriesModel> children = parentDict.getChildren();
        // 处理子项
        for (DictSeriesModel child : children) {
            // 得到字典项对应的 BackCourseModel 列表
            List<BackCourseModel> subjectCourses = backCourseMap.get(child.getId());
            if (subjectCourses != null) {
                // 将 BackCourseModel 对象列表加入到字典项中
                child.getSeriesCourseModels().addAll(subjectCourses);
            }
            // 递归调用处理子项的子项
            organizeChildren(child, dictMap, backCourseMap);
        }
    }
}
